package com.zj.processors;

import com.zj.bean.TableColumnInfo;
import com.zj.bean.TableInfo;
import com.zj.job.CodeSnippetJob;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.springframework.stereotype.Component;

import java.io.StringWriter;

@Component
public class BookingProcessor extends BaseProcessor implements TemplateProcessor{


    @Override
    public String getName() {
        return "booking-vm";
    }

    @Override
    public String process(TableInfo tableInfo, CodeSnippetJob codeSnippetJob) {
        bookingProcess(tableInfo,codeSnippetJob, "template-code-snippet/booking-model.vm");

        return "ok";
    }

    public String bookingProcess(TableInfo tableInfo, CodeSnippetJob codeSnippetJob,String template){
        Template vmTemplate = loadTemplate(template);
        boolean isFirst=true;
        for (TableColumnInfo tableColumnInfo : tableInfo.getTableColumnInfoList()) {
            String fieldName = lowFirstChar(convertDomainName(tableColumnInfo.getName()));
            if("createTime".equals(fieldName)){
                continue;
            }
            if("isDelete".equals(fieldName)){
                continue;
            }
            if("createUser".equals(fieldName)){
                continue;
            }
            if("updateTime".equals(fieldName)){
                continue;
            }
            if("updateUser".equals(fieldName)){
                continue;
            }
            VelocityContext context = new VelocityContext();
            if(isFirst){
                context.put("primaryComment","/**主键*/");
                context.put("primary","@TableId(type = IdType.AUTO)");
                isFirst=false;
            }
            context.put("comment",tableColumnInfo.getComment());
            context.put("type",toJavaType(tableColumnInfo.getType()));
            context.put("fieldName",fieldName);
            StringWriter stringWriter = new StringWriter();
            vmTemplate.merge(context,stringWriter);
            codeSnippetJob.log(stringWriter.toString());
        }
        return "ok";
    }

    private String toJavaType(String dbType) {
        dbType=dbType.toLowerCase();
        if (dbType.contains("(")) {
            dbType = dbType.substring(0, dbType.indexOf("("));
        }
        switch (dbType) {
            case "varchar":
                return "String";
            case "bigint":
                return "Long";
            case "datetime":
                return "Date";
            case "date":
                return "Date";
            case "char":
                return "String";
            case "int":
                return "Integer";
            case "text":
                return "String";
            case "tinyint":
                return "Byte";
        }

        return "unkown-"+dbType;
    }
}
